import Vue from 'vue'
import Vuex from 'vuex'
import { BLOCKED_ACCOUNTS } from '@/utils/api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    accounts: {},
    selectedAccount: localStorage.getItem('selectedAccount') || '',
    goodsList: [],
    currentGoods: null
  },
  mutations: {
    setAccounts(state, accounts) {
      state.accounts = accounts
    },
    setSelectedAccount(state, account) {
      state.selectedAccount = account
      // 将选中的账户保存到本地存储
      localStorage.setItem('selectedAccount', account)
    },
    setGoodsList(state, goodsList) {
      state.goodsList = goodsList
    },
    setCurrentGoods(state, goods) {
      state.currentGoods = goods
    }
  },
  actions: {
    async fetchAccounts({ commit, state }) {
      try {
        const response = await Vue.prototype.$http.get('/api/goods/accounts')
        if (response.data.success) {
          const accounts = response.data.accounts
          
          // 过滤账户 - 先排除屏蔽的地址
          const filteredAccounts = {...accounts};
          BLOCKED_ACCOUNTS.forEach(address => {
            delete filteredAccounts[address];
          });
          
          // 限制账户数量为5个
          const accountKeys = Object.keys(filteredAccounts);
          if (accountKeys.length > 5) {
            console.log('账户数量超过5个，进行截断处理');
            // 仅保留前5个账户
            const limitedAccounts = {};
            accountKeys.slice(0, 5).forEach(key => {
              limitedAccounts[key] = filteredAccounts[key];
            });
            commit('setAccounts', limitedAccounts);
            console.log('账户列表已限制为5个:', Object.keys(limitedAccounts));
          } else {
            commit('setAccounts', filteredAccounts);
            console.log('账户列表未超过5个，无需限制:', Object.keys(filteredAccounts));
          }
          
          // 仅当本地存储中没有选中账户或账户不存在时，才选择第一个账户
          const finalAccounts = state.accounts;
          if (!state.selectedAccount || !finalAccounts[state.selectedAccount]) {
            if (Object.keys(finalAccounts).length > 0) {
              commit('setSelectedAccount', Object.keys(finalAccounts)[0])
            }
          }
        } else {
          console.error('获取账户失败:', response.data.message)
        }
      } catch (error) {
        console.error('获取账户失败:', error)
      }
    },
    
    async fetchGoodsList({ commit, state }) {
      try {
        if (!state.selectedAccount) return
        
        console.log('正在获取商品列表，使用账户:', state.selectedAccount)
        const response = await Vue.prototype.$http.get(`/api/goods/api/goods/list?account=${state.selectedAccount}`)
        
        if (response.data.success) {
          const allGoods = response.data.goods || []
          
          // 过滤掉无效的商品数据（只过滤掉没有名称的记录）
          const validGoods = allGoods.filter(good => {
            // 只检查商品是否有名称，不再限制ID为0
            const hasValidName = good && good.name && good.name.trim() !== "";
            return hasValidName;
          });
          
          console.log(`获取商品列表成功，总数: ${allGoods.length}，有效商品: ${validGoods.length}`);
          if (allGoods.length !== validGoods.length) {
            console.log('已过滤掉无效商品记录:', allGoods.length - validGoods.length);
          }
          
          commit('setGoodsList', validGoods)
        } else {
          console.error('获取商品列表失败:', response.data.message)
          commit('setGoodsList', [])
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        commit('setGoodsList', [])
      }
    },
    
    async fetchGoodsDetail({ commit, state }, goodsId) {
      try {
        if (!state.selectedAccount) return
        
        console.log('正在获取商品详情，ID:', goodsId, '账户:', state.selectedAccount)
        
        // 确保goodsId是字符串类型
        const goodsIdStr = goodsId.toString();
        const response = await Vue.prototype.$http.get(`/api/goods/get?goodsId=${goodsIdStr}&account=${state.selectedAccount}`)
        
        if (response.data.success) {
          const goods = response.data.goods
          console.log('获取商品详情成功:', goods)
          
          // 验证商品数据的有效性 (注意：ID为0的是有效商品)
          if (!goods || goods.id === undefined || goods.id === null || goods.id === "-1" || !goods.name || goods.name.trim() === "") {
            console.error('商品数据无效或为空记录')
            commit('setCurrentGoods', null)
            return;
          }
          
          // 确保商品数据格式正确
          if (goods) {
            // 确保ID是数字
            goods.id = typeof goods.id === 'string' ? parseInt(goods.id) : goods.id
            
            // 确保historyOwners和ownershipTimestamps存在且是数组
            if (!goods.historyOwners || !Array.isArray(goods.historyOwners)) {
              goods.historyOwners = []
            }
            
            if (!goods.ownershipTimestamps || !Array.isArray(goods.ownershipTimestamps)) {
              goods.ownershipTimestamps = []
            }
          }
          
          commit('setCurrentGoods', goods)
        } else {
          console.error('获取商品详情失败:', response.data.message)
          commit('setCurrentGoods', null)
        }
      } catch (error) {
        console.error('获取商品详情失败:', error)
        commit('setCurrentGoods', null)
      }
    }
  },
  modules: {
  }
}) 